import { apiUrl } from '@/configs/index.ts'

import type { BaseResponse } from '@/types/api.d.ts'

const errorResponse : BaseResponse = {
	code: 0,
	msg: '请求失败',
	data: null,
}

class Http {
	constructor() {
		this.addInterceptor()
	}

	addInterceptor() : void {
		uni.addInterceptor('request', {
			invoke(args) {
				const token = uni.getStorageSync('token')

				args.url = `${apiUrl}${args.url}?token=${token}`
			},
		})
	}

	async get<T = any>(url : string, params ?: object) {
		return new Promise<BaseResponse<T>>((resolve) => {
			uni.request({
				url,
				data: params,
				method: 'GET',
				success: (res) => {
					if (res.statusCode === 200) {
						resolve(res.data as BaseResponse<T>)
					} else {
						resolve(errorResponse)
					}
				},
				fail: (_) => {
					resolve(errorResponse)
				},
			})
		})
	}

	async post<T = any>(url : string, data ?: object) {
		return new Promise<BaseResponse<T>>((resolve) => {
			uni.request({
				url,
				data,
				method: 'POST',
				success: (res) => {
					if (res.statusCode === 200) {
						resolve(res.data as BaseResponse<T>)
					}else if(res.statusCode==401){
							uni.reLaunch({url:'/pages/user/role/role'})
					} else {
						resolve(errorResponse)
					}
				},
				fail: (_) => {
					resolve(errorResponse)
				},
			})
		})
	}

	onSuccess(res : UniApp.RequestSuccessCallbackResult) {
		res.data
	}
}

export type HttpGet = typeof Http.prototype.get
export type HttpPost = typeof Http.prototype.post

const install = () => {
	const http = new Http()

	uni.$u.get = http.get
	uni.$u.post = http.post
}

export default {
	install,
}
